package com.shanshan.community.service;

import com.shanshan.community.entity.LoginTicket;
import com.shanshan.community.entity.User;
import com.shanshan.community.mapper.LoginTicketMapper;
import com.shanshan.community.mapper.UserMapper;
import com.shanshan.community.util.CommunityConstant;
import com.shanshan.community.util.CommunityUtil;
import com.shanshan.community.util.MailClient;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

@Service
public class UserService implements CommunityConstant {

    @Autowired
    private UserMapper userMapper;

    @Resource
    private TemplateEngine templateEngine;

    @Autowired
    private MailClient mailClient;

    @Value("${community.path.domain}")
    private String domain;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Autowired
    private LoginTicketMapper loginTicketMapper;

    public User findUserById(int id) {
        return userMapper.selectById(id);
    }

    public Map<String, Object> register(User user) {
        Map<String, Object> map = new HashMap<>();
        //空值处理
        if (user == null) {
            throw new IllegalArgumentException("参数不能为空");
        }
        if (StringUtils.isBlank(user.getUsername())) {
            map.put("usernameMsg", "账号不能为空");
            return map;
        }
        if (StringUtils.isBlank(user.getPassword())) {
            map.put("passwordMsg", "密码不能为空");
        }
        if (StringUtils.isBlank(user.getEmail())) {
            map.put("emailMsg", "邮箱不能为空");
        }

        //验证账号
        User u = userMapper.selectByName(user.getUsername());
        if (u != null) {
            map.put("usernameMsg", "该账号已存在");
        }
        //验证邮箱
        u = userMapper.selectByEmail(user.getEmail());
        if (u != null) {
            map.put("emailMsg", "该邮箱已经被注册");
        }

        //注册用户
        user.setSalt(CommunityUtil.generateUUID().substring(0, 5));//生成随机字符串
        user.setPassword(CommunityUtil.md5(user.getPassword() + user.getSalt()));//MD5密码加密
        user.setStatus(0);
        user.setType(0);
        user.setActivationCode(CommunityUtil.generateUUID());
        user.setHeaderUrl(String.format("http://images.nowcoder.com/head/%dt.png", new Random().nextInt(1000)));
        userMapper.insertUser(user);

        //激活邮件
        //与activation.html有关
        Context context = new Context();
        context.setVariable("email", user.getEmail());
        String url = domain + contextPath + "/activation/" + user.getId() + "/" + user.getActivationCode();
        context.setVariable("url", url);
        String content = templateEngine.process("/mail/activation", context);
        mailClient.sendMail(user.getEmail(), "激活账号", content);
        return map;
    }

    /*激活的方法*/
    public int activation(int userId, String code) {
        User user = userMapper.selectById(userId);
        if (user.getStatus() == 1) {
            return ACTIVATION_REPEAT;
        } else if (user.getActivationCode().equals(code)) {
            userMapper.updateStatus(userId, 1);
            return ACTIVATION_SUCCESS;
        } else return ACTIVATION_FAil;
    }


    public Map<String, Object> login(String username, String password, int expiredSeconds) {
        Map<String, Object> map = new HashMap<>();
        //判断空值
        if (StringUtils.isBlank(username)) {
            map.put("usernameMsg", "账号不能为空");
            return map;
        }
        if (StringUtils.isBlank(password)) {
            map.put("passwordMsg", "密码不能为空");
            return map;
        }

        //验证账号
        User user = userMapper.selectByName(username);
        if (user == null) {
            map.put("usernameMsg", "账号不存在");
            return map;
        }

        if (user.getStatus() == 0) {
            map.put("usernameMsg", "账号未激活");
            return map;
        }
        password = CommunityUtil.md5(password + user.getSalt());
        if (!user.getPassword().equals(password)) {
            map.put("passwordMsg", "密码不正确");
            return map;
        }

        //生成登录凭证
        LoginTicket loginTicket = new LoginTicket();
        loginTicket.setUserId(user.getId());
        loginTicket.setTicket(CommunityUtil.generateUUID());
        loginTicket.setExpired(new Date(System.currentTimeMillis() + expiredSeconds * 1000L));
        loginTicket.setStatus(0);
        loginTicketMapper.insertLoginTicket(loginTicket);
        map.put("ticket", loginTicket.getTicket());

        return map;
    }

    //根据凭证修改指定账号的登录状态
    public void logout(String ticket) {
        loginTicketMapper.updateStatus(ticket, 1);
    }


    //根据登录凭证查询
    public LoginTicket findLoginTicket(String ticket) {
        return loginTicketMapper.selectByTicket(ticket);
    }

    //更新用户头像
    public void updateHeadUrl(int userId, String headUrl) {
        userMapper.updateHead(userId, headUrl);
    }


    //更新用户密码
    public Map<String, Object> updatePassword(int userId, String iniPassword, String password1, String password2) {
        Map<String, Object> map = new HashMap<>();
        User user = userMapper.selectById(userId);
        //判断原始密码是否为空
        if (StringUtils.isBlank(iniPassword)) {
            map.put("pwdMsg", "初始密码不能为空");
            return map;
        }
        //判断初始密码是否正确
        //加密
        iniPassword = CommunityUtil.md5(iniPassword + user.getSalt());
        //判断
        if (!user.getPassword().equals(iniPassword)) {
            map.put("pwdMsg", "初始密码错误，请重新填写");
            return map;
        }
        //判断新密码是否为空
        if (StringUtils.isBlank(password1) || StringUtils.isBlank(password2)) {
            map.put("pwdMsg", "新密码不能为空");
            return map;
        }
        //验证两次输入的密码是否一致
        if (!password1.equals(password2)) {
            map.put("pwdMsg", "两次密码不一致，请重新输入。");
            return map;
        }
        //新密码加密
        password2 = CommunityUtil.md5(password2 + user.getSalt());
        //判断新旧密码是否相同
        if (iniPassword.equals(password2)) {
            map.put("pwdMsg", "新旧密码不能相同，请重新输入");
            return map;
        }
        userMapper.updatePassword(userId, password2);
        return map;
    }
}
